package com.example.demo.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.config.consts.LogConst;
import com.example.demo.config.logconfig.LogBack;
import com.example.demo.zhoushengwen.exceptionHandling.CustomException;
import com.example.demo.zhoushengwen.response.CommonCode;
import com.example.demo.zhoushengwen.utils.RequestUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 接口请求
 * 
 * @author  huxing
 * @version  [版本号, 2020年3月18日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
@Component
public class RequestLogPrintInterceptor implements HandlerInterceptor
{
    
    @Autowired
    private RequestUtil requestUtil;
    
    private long startTime = 0;
    
    /**
     * 在请求前调用
     * <p>
     * 3-4题已记录在此方法中
     * @throws Exception 
     */
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception
    {
        long begin = System.currentTimeMillis();
        startTime = begin;
        String requestParam = requestUtil.getRequestBody(request);
        LogBack.info("CLIENTIP:{}|UUID:{}|position:{}|level:{}|status:{}|method:{}|param:{}|consume:{}",
            RequestUtil.getCliectIp(request),
            response.getHeader(LogConst.LOG_UUID),
            LogConst.LOG_INTERCEPTOR,
            LogConst.LOG_STATUS_INFO,
            LogConst.LOG_BEGIN,
            request.getRequestURL().toString(),
            requestParam,
            0);
        try
        {
            //校验requestbody的json格式
            if (!StringUtils.isEmpty(requestParam))
            {
                try
                {
                    JSONObject.parseObject(requestParam);
                }
                catch (Exception e)
                {
                    JSONObject.parseArray(requestParam);
                    //如果还解析异常，就不用管，用外层异常来捕捉处理
                }
            }
            return true;
        }
        catch (Exception e)
        {
            long end = System.currentTimeMillis();
            LogBack.info("CLIENTIP:{}|UUID:{}|position:{}|level:{}|status:{}|method:{}|param:{}|consume:{}|error:{}",
                RequestUtil.getCliectIp(request),
                response.getHeader(LogConst.LOG_UUID),
                LogConst.LOG_INTERCEPTOR,
                LogConst.LOG_STATUS_ERROR,
                LogConst.LOG_END,
                request.getRequestURL().toString(),
                requestParam,
                (end - startTime),
                e);
            response.setHeader(LogConst.HANDLE_END, String.valueOf(end));
            //出现异常结束，直接走异常流程 走自定义流程
            throw new CustomException(CommonCode.PARSE_JSON_EXCEPTION);
        }
    }
    
    //当controller有异常时，不会执行
    //    @Override
    //    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
    //        ModelAndView modelAndView)
    //        throws Exception
    //    {
    //        LogBack.info("CLIENTIP:{}|UUID:{}|position:{}|level:{}|status:{}|method:{}|param:{}|consume:{}",
    //            RequestUtil.getCliectIp(request),
    //            response.getHeader(LogConst.LOG_UUID),
    //            LogConst.LOG_INTERCEPTOR,
    //            LogConst.LOG_STATUS_INFO,
    //            LogConst.LOG_END,
    //            request.getRequestURL().toString(),
    //            response.getHeader(LogConst.HANDLE_RESULT),
    //            (System.currentTimeMillis() - startTime));
    //        
    //    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception
    {
        LogBack.info("CLIENTIP:{}|UUID:{}|position:{}|level:{}|status:{}|method:{}|param:{}|consume:{}",
            RequestUtil.getCliectIp(request),
            response.getHeader(LogConst.LOG_UUID),
            LogConst.LOG_INTERCEPTOR,
            LogConst.LOG_STATUS_INFO,
            LogConst.LOG_END,
            request.getRequestURL().toString(),
            response.getHeader(LogConst.HANDLE_RESULT),
            (System.currentTimeMillis() - startTime));
        response.setHeader(LogConst.HANDLE_END, String.valueOf(System.currentTimeMillis()));
    }
    
}